package com.dudy.authdemo.service.impl;

import com.dudy.authdemo.mapper.RoleMapper;
import com.dudy.authdemo.model.Person;
import com.dudy.authdemo.model.Role;
import com.dudy.authdemo.service.PersonService;
import com.dudy.authdemo.vo.PersonVO;
import com.dudy.common.base.PageData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @program: nacos_test
 * @author: dudy
 * @create: 2020-12-22 09:42
 * @description:
 **/
@Service("personService")
public class PersonServiceImpl extends BaseServiceImpl<Person, PersonVO> implements PersonService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageData<PersonVO> selectPersonPage(PersonVO personVO, Example example) throws Exception{
        PageData<PersonVO> pageData = this.selectPageByExample(personVO, example);
        if (pageData.getTotal() > 0) {
            List<PersonVO> list = pageData.getList();
            if (CollectionUtils.isEmpty(list)) {
                return pageData;
            }else{
                list.forEach((personVo) ->{
                    String roles = personVo.getRoles();
                    if (StringUtils.isNotBlank(roles)) {
                        String[] split = roles.split(",");
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < split.length; i++) {
                            Role role = new Role();
                                    role.setRoleCode(split[i]);
                            Role role1 = roleMapper.selectOne(role);
                            sb.append(",").append(role1.getRoleName());
                        }
                        personVo.setRoleNames(sb.toString().substring(1));
                    }
                });
                pageData.setList(list);
                return pageData;
            }
        }else{
            return pageData;
        }
    }

    @Override
    public PersonVO create() {
        return new PersonVO();
    }


}
